package com.gjxx.common.utils;

import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

import java.io.UnsupportedEncodingException;

/**
 * SM3加密
 */
public class SM3Utils {

    private static final String ENCODING = "UTF-8";

    /**
     * SM3算法加密
     *
     * @param param 待加密字符串
     * @return 返回加密后，固定长度为64位的16进制字符串
     */
    public static String Encrypt(String param) {
        String result = "";

        try {
            // 将字符串转换成byte数组
            byte[] byteDatas = param.getBytes(ENCODING);
            // 调用hash
            byte[] hashDatas = hash(byteDatas);
            // 将hash值转换为16进制字符串
            result = ByteUtils.toHexString(hashDatas);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 生成hash值
     *
     * @param byteDatas 字符串
     * @return 返回长度为32的byte数组
     */
    public static byte[] hash(byte[] byteDatas) {
        SM3Digest digest = new SM3Digest();
        digest.update(byteDatas, 0, byteDatas.length);
        byte[] hashDatas = new byte[digest.getDigestSize()];
        digest.doFinal(hashDatas, 0);

        return hashDatas;
    }

}
